"""
本算法将被测对象的一组（50个）电流值数据和对应的一组（50个）有功功率数据分别存储于float型数组Irms和power中，
算法计算并输出这两组数据之间的线性相关系数r，再将线性相关系数r与预设值比较，
若r<0.95则表示相关度弱，输出0，反之则表示相关度强，输出1。
"""
from ctypes import c_float
import math
import pandas as pd

def correlation_test(Irms, power):
    cov = 0.0
    var_I = 0.0
    var_p = 0.0
    r = 0.0
    ave_I = sum(Irms) / len(Irms)
    ave_p = sum(power) / len(power)

    for i in range(len(Irms)):
        cov += (Irms[i] - ave_I) * (power[i] - ave_p)
        var_I += (Irms[i] - ave_I) ** 2
        var_p += (power[i] - ave_p) ** 2

    r = cov / math.sqrt(var_I * var_p)

    return r

def correlation_test_route(data_path):
    suffix = data_path.split(".")[1]

    # 如果输入文件是xlsx格式的。
    if suffix == "xlsx":
        data = pd.read_excel(data_path)
        Irms = data["Irms"].to_list()
        power = data["power"].to_list()
        # 将Python中的列表转换为C语言中的数组
        Irms_array = (c_float * len(Irms))(*Irms)
        power_array = (c_float * len(power))(*power)
        # 调用算法
        r = correlation_test(Irms_array, power_array)
        # 判断算法结果并输出判断值
        if r >= 0.95:
            result = 1
            # print(1)
        else:
            # print(0)
            result = 0

        result = [[{'相关性': result}]]
        return result


    #如果输入文件是txt格式的。
    if suffix == "txt":
        power = []
        Irms = []
        with open(data_path, "r", encoding='utf-8') as file:
            for line in file:
                if line.startswith("Irms:") and line.count(';') == 1:
                    parts = line.strip().split(';')
                    Irms.append(float(parts[0].split(':')[1]))
                    power.append(float(parts[1].split(':')[1]))

        # 将Python中的列表转换为C语言中的数组
        Irms_array = (c_float * len(Irms))(*Irms)
        power_array = (c_float * len(power))(*power)
        # 调用算法
        r = correlation_test(Irms_array, power_array)
        # 判断算法结果并输出判断值
        if r >= 0.95:
            result = 1
            # print(1)
        else:
            # print(0)
            result = 0

        result = [[{'相关性': result}]]
        return result


if __name__ == "__main__":
    # 读取文件路径
    # data_path = 'input_correlation_1.txt'
    data_path = 'input_correlation_0.xlsx'
    r = correlation_test_route(data_path)

    # r:线性相关度。
    print('result:', r)


